package com.dykj.fireFighting.web.firemanger;

import java.util.*;

import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.PartitionsDevice;
import com.dykj.fireFighting.api.socialUnit.devicemanger.service.IPartitionsDeviceService;
import com.dykj.fireFighting.api.socialUnit.firemanger.dto.HazardSourcesDto;
import com.dykj.fireFighting.api.socialUnit.firemanger.entity.CoordinateRelation;
import com.dykj.fireFighting.api.socialUnit.firemanger.entity.HazardSources;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.ICoordinateRelationService;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.IHazardSourcesDeviceService;
import com.dykj.fireFighting.api.socialUnit.firemanger.service.IHazardSourcesService;
import com.dykj.fireFighting.api.socialUnit.firemanger.vo.FireStationDeviceVo;
import com.dykj.fireFighting.api.socialUnit.firemanger.vo.HazardSourcesDevicedVo;
import com.dykj.fireFighting.api.socialUnit.xfyl.entity.EmergencyPlan;
import com.dykj.fireFighting.api.socialUnit.xfyl.service.IEmergencyPlanService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;



/**
 * 消防管理-危险源接口
 *
 * @Author JacksonTu
 * @Date  2021-06-25 08:34:48
 */
@Slf4j
@Api(value = "消防管理-危险源接口", tags = {"消防管理-危险源接口"})
@RestController
@RequestMapping("firemanger/hazardSources")
public class HazardSourcesController {

    @DubboReference
    private IHazardSourcesService hazardSourcesService;

    @DubboReference
    private IHazardSourcesDeviceService hazardSourcesDeviceService;

    @DubboReference
    private ICoordinateRelationService coordinateRelationService;
    @DubboReference
    private IEmergencyPlanService emergencyPlanService;
    @DubboReference
    private IPartitionsDeviceService partitionsDeviceService;

    /**
     * 获取单位id
     * @return String
     */
    public String getEnterpriseId() {
        try {
            return Long.toString(ShiroUtil.getUser().getEnterpriseId());
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }

    /**
     * 获取用户名称
     * @return String
     */
    public String getName() {
        try {
            return ShiroUtil.getUser().getName();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new BaseException("请登录系统");
        }
    }

    /**
     * 消防管理-危险源列表
     *
     * @return
     */
    @AutoLog(value = "消防管理-危险源-分页列表查询")
    @ApiOperation(value = "消防管理-危险源分页列表", notes = "消防管理-危险源分页列表")
    @GetMapping("/list")
//    @RequiresPermissions("sms/hazardSources/list")
    public CommonResult<PageVo<HazardSources>> treeGrid(HazardSourcesDto commonDto) {
        commonDto.setUnitId(getEnterpriseId());
        PageVo<HazardSources> page = hazardSourcesService.pageList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 获取消防管理-危险源信息
     */
    @AutoLog(value = "消防管理-危险源-获取消防管理-危险源信息")
    @ApiOperation(value = "获取消防管理-危险源信息", notes = "获取消防管理-危险源信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
//    @RequiresPermissions("sms/hazardSources/info")
    public CommonResult<HazardSourcesDevicedVo> info(@PathVariable("id") String id){
        HazardSources hazardSources = hazardSourcesService.getById(id);
        HazardSourcesDevicedVo hazardSourcesDevicedVo=new HazardSourcesDevicedVo();
        BeanUtils.copyProperties(hazardSources,hazardSourcesDevicedVo);
        List<String> device=hazardSourcesDeviceService.getByHazardSourcesId(id,0);
        List<String> deviceTradtion=hazardSourcesDeviceService.getByHazardSourcesId(id,1);
        hazardSourcesDevicedVo.setDevice(device);
        hazardSourcesDevicedVo.setDeviceTradition(deviceTradtion);
        if(StringUtils.isNotBlank(hazardSourcesDevicedVo.getPartitionId())){
            PartitionsDevice point = partitionsDeviceService.getPoint(hazardSourcesDevicedVo.getPartitionId(), id);
            log.info("分区关系表查询结果：{}",point.toString());
            if(point!=null){
                hazardSourcesDevicedVo.setLat( point.getX());
                hazardSourcesDevicedVo.setLng(point.getY());
            }
        }else {
            //关系表查找经纬度
            List<CoordinateRelation> coordinateRelations = coordinateRelationService.getByTableId(id, "1");
            log.info("关系表查询结果条数：{}", coordinateRelations.size());
            if (coordinateRelations.size() > 0) {
                hazardSourcesDevicedVo.setLat(coordinateRelations.get(0).getLat());
                hazardSourcesDevicedVo.setLng(coordinateRelations.get(0).getLng());
            }
        }
        if(StringUtils.isNotBlank(hazardSourcesDevicedVo.getEmergencyPlanId())){
            EmergencyPlan emergencyPlan=emergencyPlanService.getById(hazardSourcesDevicedVo.getEmergencyPlanId());
            if(emergencyPlan!=null){
                hazardSourcesDevicedVo.setEmergencyPlanName(emergencyPlan.getTitle());
            }
        }
        log.info("查询结果：{}",hazardSourcesDevicedVo.toString());
        return CommonResult.success(hazardSourcesDevicedVo);
    }

    /**
     * 保存消防管理-危险源信息
     */
    @AutoLog(value = "消防管理-危险源-保存消防管理-危险源信息")
    @ApiOperation(value = "保存消防管理-危险源信息", notes = "保存消防管理-危险源信息")
    @PostMapping("/save")
//    @RequiresPermissions("sms/hazardSources/save")
    public CommonResult save(@Valid @RequestBody HazardSourcesDevicedVo hazardSources) {
        try {
            hazardSources.setUnitId(getEnterpriseId());
            hazardSources.setCreateBy(getName());
                hazardSourcesService.insertHazardSources(hazardSources);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改消防管理-危险源信息
     */
    @AutoLog(value = "消防管理-危险源-修改消防管理-危险源信息")
    @ApiOperation(value = "修改消防管理-危险源信息", notes = "修改消防管理-危险源信息")
    @PostMapping("/update")
//    @RequiresPermissions("sms/hazardSources/update")
    public CommonResult update(@Valid @RequestBody HazardSourcesDevicedVo hazardSources) {
        try {

            hazardSources.setUpdateBy(getName());
            log.info("经度：【{}】,纬度：【{}】",hazardSources.getLng(),hazardSources.getLat());
                hazardSourcesService.updatehazardSources(hazardSources);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除消防管理-危险源信息
     */
    @AutoLog(value = "消防管理-危险源-删除消防管理-危险源信息")
    @ApiOperation(value = "删除消防管理-危险源信息", notes = "删除消防管理-危险源信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
//    @RequiresPermissions("sms/hazardSources/delete")
    public CommonResult delete(@RequestBody String[]ids) {
        try {
                hazardSourcesService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
}
